package com.dungnt.vtime.alarm;

import java.util.Calendar;

import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;

import com.dungnt.model.Alarm;
import com.dungnt.vtime.VTime;

public class AlarmService extends IntentService {

	private static final String TAG = "AlarmService";
	public static final String MAINTAIN = "MAINTAIN";
	public static final String CREATE = "CREATE";
	public static final String CANCEL = "CANCEL";

	private IntentFilter matcher;

	public AlarmService() {
		super(TAG);
		matcher = new IntentFilter();
		matcher.addAction(MAINTAIN);
		matcher.addAction(CREATE);
		matcher.addAction(CANCEL);
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		String action = intent.getAction();
		String alarmId = String.valueOf(intent.getLongExtra(Alarm.COL_ID, 0));

		Log.d("DungNT", "Alarm ID: " + alarmId);
		if (matcher.matchAction(action)) {
			if (MAINTAIN.equals(action)) {
/*				RemindMe.dbHelper
						.populate(Long.parseLong(alarmId), RemindMe.db);*/
				execute(CREATE, alarmId);
			}

			if (CREATE.equals(action)) {
				execute(CREATE, alarmId);
			}

			if (CANCEL.equals(action)) {
				execute(CANCEL, alarmId);
				//RemindMe.dbHelper.shred(RemindMe.db);
			}
		}
	}

	/**
	 * @param action
	 * @param args
	 *            {alarmId, alarmMsgId, startTime, endTime}
	 */
	private void execute(String action, String... args) {
		Intent i;
		PendingIntent pi;
		AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		//Cursor c;

		String alarmId = (args != null && args.length > 0) ? args[0] : null;
		Alarm alarm = new Alarm(Integer.parseInt(alarmId));
		alarm.load(VTime.db);

		Calendar calendar = Calendar.getInstance();		
		calendar.set(Calendar.HOUR_OF_DAY, alarm.getAlarmTime().getHour());
		calendar.set(Calendar.MINUTE, alarm.getAlarmTime().getMinute());
		
		if (CREATE.equals(action)) {
			i = new Intent(this, AlarmReceiver.class);
			i.setAction("com.dungnt.vtime." + alarmId);
			i.putExtra(Alarm.COL_ID, alarmId);
			
			
			pi = PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
			am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pi);
			Log.d("DungNT", "Set alarm action com.dungnt.vtime." + alarmId);
		}

		//c.close();
	}
}
